package com.ujiuye.config;

import com.ujiuye.utils.SecurityAccessDeniedHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.Resource;

@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true, securedEnabled = true)
public class WebSecurityConfig<main> extends WebSecurityConfigurerAdapter {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private SecurityAccessDeniedHandler securityAccessDeniedHandler;

    @Bean
    protected PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();//BCrypt强哈希算法来加密密码
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    //权限相关的
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().frameOptions().sameOrigin();
        http.csrf().disable()
                .formLogin().loginPage("/login.html")
                .loginProcessingUrl("/login")
                .defaultSuccessUrl("/index.html").permitAll()
                .failureUrl("/loginerror.html")
                .and()
                .authorizeRequests()
                .antMatchers("/login.html","/loginerror.html","/login","/loginstyle/**").permitAll()
//                .antMatchers("/css/**","/img/**","/js/**","/plugins/**").permitAll()
                .anyRequest()
                .authenticated();
        http.exceptionHandling().accessDeniedHandler(securityAccessDeniedHandler);
        http.logout().logoutUrl("/logout").logoutSuccessUrl("/login.html");
    }
}